<?php

namespace app\acc\controller;

use app\common\logic\LiXinLogic;
use think\Cache;
use think\Log;
use think\Request;
use think\Db;
use think\AjaxPage;
use think\Page;

class Index extends Sign
{
    public $miner_list = [];

    public function _initialize()
    {
        parent::_initialize();
        $user = $this->getAccount();

        $user_info = M('member')->where(array('id' => $user['id'], 'isDelete' => 2))->find();
        if (empty($user_info)) {
            $this->redirect(U('Login/exitLogin'));
        }

        $this->user = $user;
        $this->user_id = $user['id'];
    }

    public function dc_static_release()
    {
        return;
        $time = strtotime(date("Y-m-d", time()));
        set_time_limit(0);
        ini_set('memory_limit', '1024M');

        $t1 = microtime(true);

        //查找释放会员、矿机
        $WorldLogic = new \app\common\logic\WorldLogic();
        $WorldLogic->get_release_miner($time);
        //开始进行释放
        $result = $WorldLogic->start_release_miner();
        $t2 = microtime(true);
        echo '耗时' . round($t2 - $t1, 3) . '秒';
        if ($result) {
            //继续执行
//            header('Refresh: 1; url=' . U('Dcworld/Index/dc_static_release'));//三秒以后跳转百度
        }
    }

    public function index()
    {
        $user = $this->user;
        $isReal = Db::name('member')->where(['id' => $user['id']])->value('isReal');
        $today = date('Y-m-d');
        $info = Db::name('balancelog')
                    ->where([
                        'userId' => $user['id'],
                        'type' => 21,
                        'createTime' => ['like',$today.'%']
                        ])
                    ->find();
        $status = 0;
        if ($info) {
            $status = 1;
        }
        $miners = Db::name('world_miner')->where(['is_on_sale' => 1,'type' => 1,'is_del' => 0])->order('sort')->select();
        foreach ($miners as $k=>$v){
            $miners[$k]['kj_speed'] = $v['token'] * $v['token_speed'];
        }
        $this->assign('status',$status);
        // $this->assign('news', $news);
        $this->assign('miners', $miners);
        $this->assign('user', $user);
        $this->assign('isReal', $isReal);
        return $this->fetch();
    }

    /*
     * 资讯列表
     */
    public function news(){
        if (IS_POST){
            $where =[ 'cat_id' => 13,'is_open' =>1, 'publish_time' => ['LT', time()]];
            $count = Db::name('article')
                ->where($where)
                ->count();
            $Page = new Page($count,15);

            $list = Db::name('article')
                ->field('article_id,title,description,thumb,add_time')
                ->where($where)
                ->order('add_time DESC')
                ->limit($Page->firstRow.','.$Page->listRows)
                ->select();
            $this->assign('list',$list);

            return $this->fetch('ajax_news');
        }
        return $this->fetch();
    }

    /**
     * 新闻详情
     */
    public function news_info()
    {
        $id = input('id');
        if (!$id) {
            $this->error('异常');
        }
        $info = Db::name('article')->find($id);
        $this->assign('info',$info);
        return $this->fetch();
    }

    /**
     * 我的二维码
     */
    public function share()
    {
        $user = $this->user;

        if (IS_POST) {

            die;
        }
        //加载第三方类库
        vendor('phpqrcode.phpqrcode');

        //获取个人
//        $url = request()->domain().U('Lixin/Login/register',['id'=>$this->user_id]);
        $url = request()->domain().U('Login/register',['id'=>$this->user_id]);
        $codeUrl = request()->domain();

        $after_path = 'public/qrcode/' . md5($url) . '.png';

        //保存路径
        $path = ROOT_PATH . $after_path;

        //判断是该文件是否存在
        if (!is_file($path)) {
            //实例化
            $qr = new \QRcode();
            //1:url,3: 容错级别：L、M、Q、H,4:点的大小：1到10
            $qr::png($url, './' . $after_path, "M", 6, TRUE);

        }

        $config = worldCa('qr_poster');
        $this->assign('addstore','http://' . $_SERVER['SERVER_NAME'] . U('contactleader',['id'=>$this->user_id]));
        $this->assign('qrcodeImg', request()->domain() . '/' . $after_path);
        $this->assign('user', $user);
        $this->assign('codeUrl', $codeUrl);
        $this->assign('poster_bg', $config['poster_bg']);
        return $this->fetch();

    }

    //激活矿机，跳转购买页面
    public function buy(){
        $miner_id = input('id/d');
        //查询该矿机信息
        $miner = Db::name('world_miner')->where(['miner_id' => $miner_id,'is_on_sale' => 1,'type' => 1,'is_del' => 0])->find();
        $this->assign('miner', $miner);
        $this->assign('title', '激活矿机');
        return $this->fetch();
    }

    /**
     * 购买矿机
     */
    public function activate()
    {
        $user_id = $this->user_id;
        if ($user_id) {
            //查询用户信息
            $user = Db::name('member')->field('id,account,miner,kj_all_token,parentId,isReal,all_calculation,give_calculation,max_calculation')->find($user_id);
            if (!$user['isReal']) {
                exit(json_encode(['code' => -1, 'msg' =>'请先实名认证']));
            }
            if ($user){
                $res_all_token = Db::name('all_token')->find();
                $miner_id = input('post.id');
                $miner_price = input('post.miner_price/d');
                //查询用户是否已购买矿机，如果购买提示不能购买
                $isBuyMiner = Db::name('user_miner')->where(['user_id'=>$user_id])->find();
                if (!empty($isBuyMiner)){
                    exit(json_encode(['code' => -1, 'msg' =>'每人限购一台矿机！']));
                }
                //查询该矿机信息
                $miner = Db::name('world_miner')->where(['miner_id' => $miner_id,'is_on_sale' => 1,'type' => 1,'is_del' => 0])->find();
                if (empty($miner)){
                    exit(json_encode(['code' => -1, 'msg' =>'矿机不存在']));
                }
                if ($user['miner'] < $miner_price) {
                    exit(json_encode(['code' => -1, 'msg' =>'余额不足以激活']));
                }
                if ($miner_price < intval($miner['min'])){
                    exit(json_encode(['code' => -1, 'msg' =>'购买量不得小于最小购买量']));
                }
                if ($miner_price > intval($miner['max'])){
                    exit(json_encode(['code' => -1, 'msg' =>'购买量不得大于最大购买量']));
                }
                if ($res_all_token['total'] - $miner_price <= 0){
                    exit(json_encode(['code' => -1, 'msg' =>'矿机已禁止购买']));
                }
                // 添加购买订单记录
                $orderData = [
                    'order_sn'=> $this->get_order_sn(),
                    'user_id' => $user_id,
                    'goods_price' => $miner_price,
                    'order_amount' => $miner_price,
                    'pay_code' => 'miner',
                    'pay_name' => '矿池钱包支付',
                    'add_time' => time(),
                    'pay_time' => time(),
                ];
                $order_id = Db::name('world_order')->insertGetId($orderData);
                // 扣矿池钱包 加记录 添加购买订单记录  添加用户矿机
                $after  = bcsub($user['miner'],$miner_price, 2);
                if ($after<0) {
                    exit(json_encode(['code' => -1, 'msg' =>'余额不足以激活']));
                }
                // 添加矿池钱包扣除记录
                $minerLog = minerlog($order_id, $user_id, -$miner_price, 1, $user['miner'],$after, '购买矿机扣除');
                $userData = ['miner' => $after];
                $userData['kj_all_token'] = $user['kj_all_token'] + ($miner['multiple']*$miner_price);    //用户总token添加
                //直推用户收益
                $ztUser = $this->countUserParentReceive($user['parentId'], $miner_price);
                //计算新增业绩
                $userLevel = Db::name('world_level')->where('level_id', $user['level'])->find();
                $resyjSize = $this->yjSize($user_id,$user['parentId'],$miner_price,$userLevel['id']);
                // 更改用户钱包值、矿机总token
                $userRes = Db::name('member')->where(['id' => $user_id])->save($userData);
                // 添加用户矿机
                $minerData = [
                    'sn' => $this->getMinerSn(),
                    'user_id'=>$user_id,
                    'add_time' => time(),
                    'receive'=>0,
                    'receive_time'=>time(),
                    'miner_id'=>$miner['miner_id'],
                    'miner_price'=>$miner_price,
                    'kj_token'=>$miner['multiple']*$miner_price,
                    'kj_token_speed'=>$miner['token_speed'],
                ];

                $userMinerRes = Db::name('user_miner')->insertGetId($minerData);
                if ($order_id && $minerLog && $userRes &&$userMinerRes &&$ztUser ){
                    $shengYu = $res_all_token['total'] - $miner['multiple'] * $miner_price;
                    Db::name('all_token')->where(['id' => $res_all_token['id']])->update(['total' => $shengYu]);
                    $tokenLogData = [
                        'userId' => $user_id,
                        'createTime' => date("Y-m-d H:i:s",time()),
                        'miner_id' => $miner['miner_id'],
                        'kj_token' => $miner['multiple'] * $miner_price,
                        'desc' => '购买矿机扣除'
                    ];
                    Db::name('all_token_log')->insert($tokenLogData);
                    exit(json_encode(['code' => 1, 'msg' =>'激活成功']));
                }
            }
        }
        exit(json_encode(['code' => -1, 'msg' =>'请稍候尝试']));
    }

    /**
     * 升级矿机
     * */
    public function upgrade(){
        $miner_id = input('id/d');
        //查询该矿机信息
        $miner = Db::name('world_miner')->where(['miner_id' => $miner_id,'is_on_sale' => 1,'type' => 1,'is_del' => 0])->find();
        $this->assign('miner', $miner);
        $this->assign('title', '升级矿机');
        return $this->fetch();
    }

    //升级操作
    public function upgradeSubmit(){
        $user_id = $this->user_id;
        if ($user_id) {
            //查询用户信息
            $user = Db::name('member')->field('id,account,miner,level,kj_all_token,parentId,isReal,all_calculation,give_calculation,max_calculation')->find($user_id);
            if (!$user['isReal']) {
                exit(json_encode(['code' => -1, 'msg' =>'请先实名认证']));
            }
            if ($user){
                $res_all_token = Db::name('all_token')->find();
                $miner_id = input('post.id');
                $miner_price = input('post.miner_price');
                //查询用户是否已买矿机
                $userMiner = Db::name('user_miner')->where(['user_id'=>$user_id])->find();
                //查询该矿机信息
                $miner = Db::name('world_miner')->where(['miner_id' => $miner_id,'is_on_sale' => 1,'type' => 1,'is_del' => 0])->find();
                if (empty($userMiner)){
                    exit(json_encode(['code' => -1, 'msg' =>'请您先购买矿机！']));
                }
                //不得升级同一台矿机
                if ($userMiner['miner_id'] == $miner_id){
                    exit(json_encode(['code' => -1, 'msg' =>'请您升级其他矿机！']));
                }
                $userMInerInfo = Db::name('world_miner')->where(['miner_id' => $userMiner['miner_id'],'is_on_sale' => 1,'type' => 1,'is_del' => 0])->find();
                if ($userMInerInfo['min'] > $miner['min']){
                    exit(json_encode(['code' => -1, 'msg' =>'升级矿机不得小于已购矿机']));
                }
                if ($miner_price < intval($miner['min'])){
                    exit(json_encode(['code' => -1, 'msg' =>'购买量不得小于最小购买量']));
                }

                if ($miner_price > intval($miner['max'])){
                    exit(json_encode(['code' => -1, 'msg' =>'购买量不得大于最大购买量']));
                }
                //升级矿机，实际支付为补差价，用现实际购买金额 - 上一台矿机金额
                $pay_price = $miner_price - $userMiner['miner_price'];
                if ($user['miner'] < $pay_price) {
                    exit(json_encode(['code' => -1, 'msg' =>'余额不足以升级']));
                }
                if ($res_all_token['total'] - $miner_price <= 0){
                    exit(json_encode(['code' => -1, 'msg' =>'矿机已禁止购买']));
                }
                // 添加购买订单记录
                $orderData = [
                    'order_sn'=> $this->get_order_sn(),
                    'user_id' => $user_id,
                    'goods_price' => $pay_price,
                    'order_amount' => $pay_price,
                    'pay_code' => 'miner',
                    'pay_name' => '矿池钱包支付',
                    'add_time' => time(),
                    'pay_time' => time(),
                ];
                $order_id = Db::name('world_order')->insertGetId($orderData);
                // 扣矿池钱包 加记录 添加购买订单记录  添加用户矿机
                $after  = bcsub($user['miner'],$pay_price, 2);
                if ($after<0) {
                    exit(json_encode(['code' => -1, 'msg' =>'余额不足以激活']));
                }
                //添加操作记录
                $operate = '升级矿机扣除矿池钱包 -'.$pay_price;
                $this->addOperateLog($user_id, $user['account'], $operate, $user['miner'], $after);
                // 添加矿池钱包扣除记录
                $minerLog = minerlog($order_id, $user_id, -$pay_price, 1, $user['miner'],$after, '升级矿机扣除');
                $userData['miner'] = $after;
//                $userData['kj_all_token'] = $user['kj_all_token'] + ($miner['multiple'] * $pay_price) - $userMiner['kj_already_token'];    //用户总token添加----减去升级前矿机已产收益
                $userData['kj_all_token'] = $user['kj_all_token'] + ($miner['multiple'] * $pay_price);
                //直推用户收益
                $ztUser = $this->countUserParentReceive($user['parentId'], $pay_price);
                //业绩奖
                $userLevel = Db::name('world_level')->where('level_id', $user['level'])->find();
                $yjSize = $this->yjSize($user_id,$user['parentId'],$pay_price, $userLevel['id']);
                // 更改用户钱包值、矿机总token
                $userRes = Db::name('member')->where(['id' => $user_id])->save($userData);
                // 添加用户矿机
                $minerData = [
                    'sn' => $this->getMinerSn(),
                    'user_id' => $user_id,
                    'add_time' => time(),
                    'receive' => 0,
                    'receive_time' => time(),
                    'miner_id' => $miner['miner_id'],
                    'miner_price' => $miner_price,
                    'kj_token' => $miner['multiple'] * $miner_price + $userMiner['kj_token'],
                    'kj_token_speed' => $miner['token_speed'],
                ];

                $res_delete = Db::name('user_miner')->where('id', $userMiner['id'])->delete();

                $userMinerRes = Db::name('user_miner')->insertGetId($minerData);
                if ($order_id && $minerLog && $userRes &&$userMinerRes &&$ztUser && $res_delete){
                    $shengYu = $res_all_token['total'] - $miner['multiple'] * $miner_price;
                    Db::name('all_token')->where(['id' => $res_all_token['id']])->update(['total' => $shengYu]);
                    $tokenLogData = [
                        'userId' => $user_id,
                        'createTime' => date("Y-m-d H:i:s",time()),
                        'miner_id' => $miner['miner_id'],
                        'kj_token' => $miner['multiple'] * $miner_price,
                        'desc' => '升级矿机扣除'
                    ];
                    Db::name('all_token_log')->insert($tokenLogData);
                    exit(json_encode(['code' => 1, 'msg' =>'升级成功']));
                }
            }
        }
        exit(json_encode(['code' => -1, 'msg' =>'请稍候尝试']));
    }

    /**
     * 计算直推用户收益
     * parentId：用户直推id
     * miner_id：矿机id
     * */
    public function countUserParentReceive($parentId, $miner_price){
        //查询直推用户信息
        $userParent =  Db::name('member')->where('id', $parentId)->field('id,account,miner,kj_all_token,all_receive,parentId')->find();
        if (!empty($userParent)){
            //查询直推用户购买矿机总金额
            $userMiner =  Db::name('user_miner')->where(['user_id' => $userParent['id'],'status' => 1,'type' => 1])->find();
            //如上级用户未购买矿机，则不增加收益
            if (!empty($userMiner)){
                if ($userMiner['miner_price'] >= $miner_price){
                    //上级用户购买总金额大于下级用户购买金额，选取下级用户支付金额 * 0.1作为收益
                    $receive = $miner_price * 0.1;
                }else{
                    //非同类矿机
                    $receive = $userMiner['miner_price'] * 0.1;
                }
                $afterToken = ($userParent['kj_all_token'] - $receive) <= 0 ? 0 : ($userParent['kj_all_token'] - $receive);
                if ($afterToken <= 0){
                    //如果token不够扣的，则直接返回
                    return  true;
                }
                $userData = [
                    'miner' => $userParent['miner'] + $receive,           //增加用户总收益
                    'all_receive' => $userParent['all_receive'] + $receive,           //增加用户总收益
                    'kj_all_token' => $afterToken       //减少用户总token
                ];
                $result = Db::name('member')->where('id', $userParent['id'])->save($userData);
                //减少矿机token
                $dec_user_miner = ($userMiner['kj_token'] - $receive) <= 0 ? 0 : ($userMiner['kj_token'] - $receive);
                $res_user_miner = Db::name('user_miner')->where('user_id', $userParent['id'])->save(['kj_token' => $dec_user_miner]);
                if ($result && $res_user_miner){
                    minerlog(777, $userParent['id'], +$receive, 7, $userParent['miner'], $userData['miner'], '分享奖励');
                    $this->countThree($userParent['parentId'],$receive);
                    return true;
                }else{
                    return false;
                }
            }
            return true;
        }
        return true;
    }

    /**
     * 新增业绩
     * 同等级用户，拿到0.1%
     * $user_id：购买用户id
     * $parentId：购买用户父id
     * $miner_price：用户购买矿机价格
     * $userLevel: 购买用户星级等级
     * */
    public function yjSize($user_id, $parentId, $miner_price,$userLevel){
        //查询购买用户父级信息及星级等级
        $userParent = Db::name('member m')
            ->join('world_level l','m.level = l.level_id','left')
            ->where('m.id', $parentId)
            ->field('m.id,m.account,m.miner,m.kj_all_token,m.all_receive,m.parentId,m.level,l.level_id')
            ->find();
        if (!empty($userParent)){
            if ($userParent['level_id'] > 1){
                //判断父级是否星级会员，是执行此步骤
                $this->incParent($userParent['id'],$miner_price,$userParent['level_id'], $userLevel);
            }else{
                //如果直接用户不是星级会员，查找父级用户的父级
                $this->yjSize($parentId, $userParent['parentId'],$miner_price,$userLevel);
            }
        }
        return true;

    }

    /**
     * 新增业绩，拿收益的30%
     * $parentId：父id
     * $miner_price：实际购买价格
     * $parLevelId：
     * $userLevel：购买用户星级等级
     * */
    public function incParent($parentId, $miner_price, $parLevelId, $userLevel, $level = 1){
        $userParent = Db::name('member')
            ->where('id', $parentId)
            ->field('id,account,miner,kj_all_token,all_receive,parentId,level')
            ->find();
        //购买用户星级等级
        $worldLevel = Db::name('world_level')
            ->where('level_id', $userLevel)
            ->find();
        //该父级用户星级等级
        $worldLevel2 = Db::name('world_level')
            ->where('level_id', $parLevelId)
            ->find();
        if($parLevelId > $userLevel){
            if (!empty($userParent)){
                //父级星级大于购买用户星级
                if ($parLevelId > $level){
                    $Level2 = Db::name('world_level')
                        ->where('level_id', $level)
                        ->find();
                    $prize = $worldLevel2['inc_speed'] - $Level2['inc_speed'];
                    $addLevel = $worldLevel2['level_id'] - $level;
                    $profit = $miner_price * $prize / 100;
                    //增加用户总收益
                    $userData['miner'] = $userParent['miner'] + $profit;
                    $userData['all_receive'] = $userParent['all_receive'] + $profit;
                    //减少用户总token
                    $userData['kj_all_token'] = $userParent['kj_all_token'] - $profit;
                    Db::name('member')->where('id', $userParent['id'])->save($userData);
                    $userMiner = Db::name('user_miner')->where('user_id', $userParent['id'])->find();
                    $res_user_miner = Db::name('user_miner')->where('user_id', $userParent['id'])->save(['kj_token'=>($userMiner['kj_token']-$profit)]);
                    minerlog(888, $userParent['id'], +$profit, 6, $userParent['miner'], $userData['miner'], '新增管理收益');
                    $parent = Db::name('member')
                        ->where('id', $userParent['parentId'])
                        ->field('id,parentId,level')
                        ->find();
                    $parentLevel = Db::name('world_level')
                        ->where('level_id', $parent['level'])
                        ->find();
                    $res = $this->countThree2($parent['id'],$profit);
                    if ($res && $parLevelId < 4 && $res_user_miner){
                        $level += $addLevel;
                        $this->incParent($parent['id'], $miner_price, $parentLevel['level_id'], $userLevel, $level);
                    }else{
                        return true;
                    }
                }else{
                    $parent = Db::name('member')
                        ->where('id', $userParent['parentId'])
                        ->field('id,parentId,level')
                        ->find();
                    $parentLevel = Db::name('world_level')
                        ->where('level_id', $parent['level'])
                        ->find();
                    $this->incParent($parent['id'], $miner_price, $parentLevel['level_id'], $userLevel, $level);
                }
            }
        }else{
           if (!empty($userParent)){
               //如果不大于，只能获取用户收益的30%
               $profit = $miner_price * $worldLevel['inc_speed'] / 100 * 0.3;
               $parent = Db::name('member')
                   ->where('id', $userParent['parentId'])
                   ->field('id,parentId,level')
                   ->find();
               $this->countThree2($parent['id'], $profit);
               return true;
           }
        }
        return true;
    }

    /**
     * 计算上级上直推收益，30%
     * */
    public function countThree2($parentId, $profit){
        $usersParent =  Db::name('member')->where('id', $parentId)->field('id,account,miner,kj_all_token,all_receive,parentId')->find();
        if (!empty($usersParent)){
            $profit = $profit * 0.3;
            //增加用户总收益
            $userData['miner'] = $usersParent['miner'] + $profit;
            $userData['all_receive'] = $usersParent['all_receive'] + $profit;
            //减少用户总token
            $userData['kj_all_token'] = $usersParent['kj_all_token'] - $profit;
            if ($userData['kj_all_token'] <= 0){
                return true;
            }
            $result = Db::name('member')->where('id', $usersParent['id'])->save($userData);
            $userMiner =  Db::name('user_miner')->where(['user_id' => $usersParent['id'],'status' => 1,'type' => 1])->find();
            $res_user_miner = Db::name('user_miner')->where('user_id', $usersParent['id'])->save(['kj_token'=>($userMiner['kj_token']-$profit)]);
            minerlog(000, $usersParent['id'], +$profit, 6, $usersParent['miner'], $userData['miner'], '新增业绩收益奖');
            if ($result && $res_user_miner){
                $this->countThree2($usersParent['parentId'], $profit);
            }else{
                Log::info('用户购买30%，直推奖添加失败！');
            }
        }else{
            return true;
        }
        return true;
    }

    /**
     * 计算上级上直推收益，30%
     * */
    public function countThree($parentId, $profit){
        $userParent =  Db::name('member')->where('id', $parentId)->field('id,account,miner,kj_all_token,all_receive,parentId')->find();
        if (!empty($userParent)){
            $profit = $profit * 0.3;
            $userData = [
                'miner' => $userParent['miner'] + $profit,  //增加用户总收益
                'all_receive' => $userParent['all_receive'] + $profit,  //增加用户总收益
                'kj_all_token' => ($userParent['kj_all_token'] - $profit) <= 0 ? 0 : ($userParent['kj_all_token'] - $profit)     //减少用户总token
            ];
            if ($userData['kj_all_token'] <= 0){
                return true;
            }
            //更新用户表数据
            $result = Db::name('member')->where('id', $userParent['id'])->save($userData);
            //更新用户订单表数据
            $userMiner =  Db::name('user_miner')->where(['user_id' => $userParent['id'],'status' => 1,'type' => 1])->find();
            $afterUserMiner = ($userMiner['kj_token']-$profit) <= 0 ? 0 : $userMiner['kj_token']-$profit;
            $res_user_miner = Db::name('user_miner')->where('user_id', $userParent['id'])->save(['kj_token' => $afterUserMiner]);
            minerlog(999, $userParent['id'], +$profit, 6, $userParent['miner'], $userData['miner'], '管理收益');
            if ($result && $res_user_miner){
                $this->countThree($userParent['parentId'], $profit);
            }else{
                Log::info('用户购买30%，直推奖添加失败！');
            }
        }else{
            return true;
        }
    }

    /*
     * 添加操作日志
     * $user_id：用户ID
     * $account：用户账户
     * $operate：操作
     * $before_user_miner：操作前矿池钱包
     * $after_user_miner：操作后矿池钱包
     * */
    public function addOperateLog($user_id = 0, $account = 0, $operate, $before_user_miner = 0, $after_user_miner = 0){
        $param['user_id'] = $user_id;
        $param['account'] = $account;
        $param['operate'] = $operate;
        $param['before_user_miner'] = $before_user_miner;
        $param['after_user_miner'] = $after_user_miner;
        $param['add_time'] = date("Y-m-d H:i:s",time());
        Db::name('operate_log')->insert($param);
    }


    /**
     * 获取订单 order_sn
     * @return string
     */
    public function get_order_sn()
    {
        $order_sn = null;
        // 保证不会有重复订单号存在
        while (true) {
            $order_sn = date('YmdHis') . rand(1000, 9999); // 订单编号
            $order_sn_count = M('world_order')->where("order_sn = " . $order_sn)->count();
            if ($order_sn_count == 0)
                break;
        }
        return $order_sn;
    }

    /**
     * 获取订单 order_sn
     * @return string
     */
    public function getMinerSn()
    {
        $order_sn = null;
        // 保证不会有重复订单号存在
        while (true) {
            $order_sn = 'LX'.date('YmdHis'); // 订单编号
            $order_sn_count = M('user_miner')->where(['sn'=>$order_sn])->count();
            if ($order_sn_count == 0)
                break;
        }
        return $order_sn;
    }

    public function baseUploadImg()
    {
        $user_id = $this->user_id;
        $data = I("post.");
        //头像更改
        $base64 = $data['head_img'];
        $dir = 'public/upload/profilePhoto/';

        apilog($data, $user_id, '上传头像');
        $result = base64_image_content($base64, $dir);

        if ($result) {
            $post['profilePhoto'] = $result;
            M('member')->where(array('id' => $user_id))->update($post);
            $result = ['status' => 1, 'data' => $result];
            $this->ajaxSuccess($result);
        }
    }


    public function test()
    {
         $logic = new \app\common\logic\LiXinLogic();
         $miner = Db::name('world_miner')->where(['miner_id' => 10,'is_on_sale' => 1,'type' => 1,'is_del' => 0])->order('sort')->find();
        $result = $logic->updateLevel(2090,$miner);
    }

    //算力页面
    public function world_power()
    {
        $user = session('account');
        $user_info = M('member')->where(array('id' => $user['id']))->find();
        $general_income = M('world_power_log')->where(array('user_id' => $user_info['id'], 'number' => array('gt', 0)))->sum('number');
        $total_expenditure = M('world_power_log')->where(array('user_id' => $user_info['id'], 'number' => array('lt', 0)))->sum('number');
        //收入条件
        $type_income_list = array(
            '1' => '激活矿机',
            '2' => '激活奖励',
            '3' => '采购矿机',
            '4' => '推广奖励',
        );
        //支出条件
        $type_expend_list = array(
            '5' => '日常衰减',
            '6' => '加速衰减',
            '7' => '矿机报废'
        );

        $this->assign('type_income_list', $type_income_list);
        $this->assign('type_expend_list', $type_expend_list);
        $this->assign('cny_proportion', worldCa('basic.dc_cny_rate'));
        $this->assign('user_info', $user_info);
        $this->assign('general_income', $general_income);
        $this->assign('total_expenditure', $total_expenditure);
        return $this->fetch();
    }

    public function ajax_world_power()
    {
        //数据
        $user_info = session('account');
        $state = I('state');
        $type = I('type');
        //查询条件
        $where = array();
        $where['user_id'] = $user_info['id'];
        if ($state == 'income' || empty($state)) {
            $where['number'] = array('gt', 0);
        } elseif ($state == 'expend') {
            $where['number'] = array('lt', 0);
        }

        if ($type) {
            $where['type'] = $type;
        }

        //分页数据
        $count = db('world_power_log')->where($where)->count();
        $Page = new AjaxPage($count, 10);
        $date = db('world_power_log')->where($where)->limit($Page->firstRow, $Page->listRows)->order('log_id desc')->select();
        //$show = $Page->show(); //暂时无用

        $this->assign('date', $date);
        return $this->fetch();
    }

    /**
     * 检查是否有新消息
     */
    public function check_new_notice()
    {
        $user_id = $this->user_id;
        $notice = M('user_notice')->where(array('user_id' => $user_id, 'is_tips' => 0))->order('id desc')->find();
        if (empty($notice)) {
            $this->ajaxError('');
        }
        $this->ajaxSuccess($notice);
    }

    public function applyReal()
    {
        $user = $this->getAccount();
        $info = Db::name('apply_real')->where(['user_id' =>$user['id']])->find();
        if (IS_POST) {
            $realName = input('post.realName');
            $IDCart = input('post.IDCart');
            $ali = input('post.ali');
            $paypwd = input('post.paypwd');
            $ali = '123';
            $paypwd = '123123';
            $email = input('post.email');
            $email_code = input('post.email_code');

            if($user['email'] != $email){
                $this->ajaxError('输入邮箱与绑定邮箱不一致！');
            }
            //获取缓存的邮箱验证码
            $cacheCode = Cache::get(':'.$email, true);
            if (empty($cacheCode)){
                $this->ajaxError('请先获取验证码！');
            }
            if ($cacheCode != $email_code){
                $this->ajaxError('取验证码错误！');
            }
            if ($realName && $IDCart && $ali && $paypwd ) {

                if (strlen($IDCart) < 15 ) {
                    exit(json_encode(['code' => -1, 'msg' => '请输入有效身份证信息']));
                }
                /*if (md5($paypwd) != $user['paypassword']) {
                    exit(json_encode(['code' => -1, 'msg' => '密码错误']));
                }*/
                $count = Db::name('apply_real')->where(['user_id' => ['NEQ',$user['id']],'IDCart' => $IDCart])->find();
                if ($count){
                    exit(json_encode(['code' => -1, 'msg' => '当前身份证已被注册']));
                }
                Db::name('member')->where(['id' => $user['id']])->update(['nickname' => $realName, 'isReal' => 1]);

                // 校验当前是否含有待审核状态
                if ($info) {
                    if ($info['status']  == 0) {
                        exit(json_encode(['code' => -1, 'msg' => '当前已有待申请记录，请耐心等待哦']));
                    }
                    if ($info['status'] == 1) {
                        exit(json_encode(['code' => -1, 'msg' => '您已通过申请']));
                    }
                    $applyData = [
                        'realName' => $realName,
                        'IDCart' => $IDCart,
                        'ali'   => $ali,
                        'paypwd' => $paypwd,
                        'status' => 0,
                        'update_time' => time()
                    ];
                    $res = Db::name('apply_real')->where(['id' => $info['id']])->update($applyData);
                } else {
                    // 验证通过 准备入库
                    $applyData = [
                        'user_id' => $user['id'],
                        'realName' => $realName,
                        'IDCart' => $IDCart,
                        'ali'   => $ali,
                        'paypwd' => $paypwd,
                        'status' => 1,
                        'add_time' => time(),
                        'update_time' => time()
                    ];
                    $res = Db::name('apply_real')->insertGetId($applyData);
                }
                if ($res) {
                    exit(json_encode(['code' => 1, 'msg' => '审核通过！']));
                }
                exit(json_encode(['code' => -1, 'msg' => '提交失败，请稍候尝试']));
            } else {
                exit(json_encode(['code' => -1, 'msg' => '请填写完整信息']));
            }
        }

        if ($info) {
            if ($info['status'] === 0) $statusName = '待审核';
            if ($info['status'] === 1) $statusName = '审核通过';
            if ($info['status'] === 2) $statusName = '审核失败';
        } else {
            $statusName = '待实名';
        }

        $this->assign('info', $info);
        $this->assign('user', $user);
        $this->assign('statusName', $statusName);
        return $this->fetch();

    }

    public function systemReport()
    {
        if (IS_POST){
            $where =[ 'cat_id' => 12,'is_open' =>1, 'publish_time' => ['LT', time()]];
            $count = Db::name('article')
                ->where($where)
                ->count();
            $Page = new Page($count,15);

            $list = Db::name('article')
                ->field('article_id,title,description,thumb,add_time')
                ->where($where)
                ->order('add_time DESC')
                ->limit($Page->firstRow.','.$Page->listRows)
                ->select();
            $this->assign('list',$list);

            return $this->fetch('ajax_report');
        }
        return $this->fetch();
    }

    public function onlineService()
    {
        $config = Db::name('world_system')->where(['inc_type' => 'miner_basic', 'name' => 'onlineService'])->value('value');
        $this->assign('config',$config);
        return $this->fetch();
    }
}
